import CryptoJS from 'crypto-js';

// 加密
export function generatekey(num) {
	const library = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	let key = '';
	for (let i = 0; i < num; i++) {
		const randomPoz = Math.floor(Math.random() * library.length);
		key += library.substring(randomPoz, randomPoz + 1);
	}
	return key;
}

// 加密
export function encrypt(word, keyStr) {
	// 判断是否存在keyStr，不存在就用默认的keyStr（注意：这个keyStr必需要前后端统一，不然双方加密解密后会不相同。调用generatekey方法生成）
	keyStr = keyStr ? keyStr : '1grLx91U40VawzhRAm7E';
	const key = CryptoJS.enc.Utf8.parse(keyStr);
	const srcs = CryptoJS.enc.Utf8.parse(word);
	const encrypted = CryptoJS.AES.encrypt(srcs, key, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7,
	});
	return encrypted.toString();
}

// 解密
export function decrypt(word, keyStr) {
	keyStr = keyStr ? keyStr : '1grLx91U40VawzhRAm7E';
	const key = CryptoJS.enc.Utf8.parse(keyStr);
	const decrypt = CryptoJS.AES.decrypt(word, key, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7,
	});
	return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}